package com.souku.finance.application.widget;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.souku.finance.application.R;
import com.souku.finance.application.bean.IndexBean;

import java.util.ArrayList;
import java.util.List;

import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;

/**
 * Created by Administrator on 2016/8/11.
 */
public class BannerViewPager extends FrameLayout {

    /**
     * startAutoScroll() 启动自动滚动
     * stopAutoScroll() 停止自动滚动
     * <p/>
     * setInterval(long) 设置自动滚动的间隔时间，单位为毫秒
     * setDirection(int) 设置自动滚动的方向，默认向右
     * setCycle(boolean) 是否自动循环轮播，默认为true
     * setAutoScrollDurationFactor(double) 设置ViewPager滑动动画间隔时间的倍率，达到减慢动画或改变动画速度的效果
     * setStopScrollWhenTouch(boolean) 当手指碰到ViewPager时是否停止自动滚动，默认为true
     * setSlideBorderMode(int) 滑动到第一个或最后一个Item的处理方式，支持没有任何操作、轮播以及传递到父View三种模式
     * setBorderAnimation(boolean) 设置循环滚动时滑动到从边缘滚动到下一个是否需要动画，默认为true
     */
    protected AutoScrollViewPager autoScrollViewPager;
    protected LinearLayout pointGroup;
    protected RelativeLayout rlPointBg;
    protected TextView tvTitle;
//    protected CirclePageIndicator indicator;

    protected LinearLayout points;

    protected ArrayList<ImageView> pagerViews;
    protected List<IndexBean.BannersBean> bannerDatas;

    protected int lastPosition;


    public BannerViewPager(Context context) {
        super(context);
        init(context, null);
    }

    public BannerViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public BannerViewPager(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        LayoutInflater.from(context).inflate(R.layout.widget_banner_viewpager, this);
        autoScrollViewPager = (AutoScrollViewPager) findViewById(R.id.auto_scroll_viewpager);
        autoScrollViewPager.setInterval(2500);
        autoScrollViewPager.setAutoScrollDurationFactor(5);
        autoScrollViewPager.setStopScrollWhenTouch(true);
//        autoScrollViewPager.setBorderAnimation(false);
//        autoScrollViewPager.setOffscreenPageLimit(1);//预加载

        pointGroup = (LinearLayout) findViewById(R.id.point_group);
        rlPointBg = (RelativeLayout) findViewById(R.id.rl_point_bg);
        tvTitle = (TextView) findViewById(R.id.tv_title);
//        rlPointBg.getBackground().setAlpha(180);
//        indicator = (CirclePageIndicator) findViewById(R.id.indicator);
//        final float density = getResources().getDisplayMetrics().density;
//        indicator.setSnap(true);
//        indicator.setBackgroundColor(0xFFCCCCCC);
//        indicator.setRadius(5 * density);//设置圆的大小
//        indicator.setPageColor(0x880000FF);//未现在圆里面的填充色
//        indicator.setFillColor(0xFF888888);//选中圆的填充色
//        indicator.setStrokeColor(0xFF000000);//圆的边框颜色
//        indicator.setStrokeWidth(2 * density);//设置圆的边框宽度

        pagerViews = new ArrayList<ImageView>();

    }

    public AutoScrollViewPager getAutoScrollViewPager() {
        return autoScrollViewPager;
    }

    public void setBannerData(final List<IndexBean.BannersBean> bannerDatas) {
        this.bannerDatas = bannerDatas;

        if (bannerDatas != null) {
            final List<String> imagePaths = new ArrayList<String>();
            for (int i = 0; i < bannerDatas.size(); i++) {
                imagePaths.add(bannerDatas.get(i).getListImage());
            }
            setImagePaths(imagePaths);
        }

    }

    private void setImagePaths(List<String> imagePaths) {

        pagerViews.clear();
        pointGroup.removeAllViews();

        for (int i = 0; i < imagePaths.size(); i++) {
            final int p = i;
            ImageView point = new ImageView(getContext());
            LinearLayout.LayoutParams pointParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);

            pointParams.rightMargin = 15;
            point.setLayoutParams(pointParams);
            point.setBackgroundResource(R.drawable.home_point_bg);
            if (i == 0) {
                point.setEnabled(true);
            } else {
                point.setEnabled(false);
            }
            pointGroup.addView(point);

            final ImageView imageView = new ImageView(getContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onImageListener != null) {
                        onImageListener.onClick(v, p);
                    }
                }
            });
            pagerViews.add(imageView);

            final String imagepath = imagePaths.get(i);
            Glide.with(getContext())
                    .load(imagepath)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .error(R.drawable.shipin)
                    .fitCenter()
                    .into(imageView);
        }

        setAdapter(pagerViews);

    }

    private OnImageListener onImageListener;

    public void setOnClickImage(OnImageListener onImageListener) {
        this.onImageListener = onImageListener;
    }

    public interface OnImageListener {
        public void onClick(View view, int p);
    }

    public void setImageResources(List<Integer> imageResources) {

        pagerViews.clear();
        pointGroup.removeAllViews();

        for (int i = 0; i < imageResources.size(); i++) {

            ImageView point = new ImageView(getContext());
            LinearLayout.LayoutParams pointParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);

            pointParams.rightMargin = 15;
            point.setLayoutParams(pointParams);
            point.setBackgroundResource(R.drawable.home_point_bg);
            if (i == 0) {
                point.setEnabled(true);
            } else {
                point.setEnabled(false);
            }
            pointGroup.addView(point);

            ImageView imageView = new ImageView(getContext());
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            pagerViews.add(imageView);

            Glide.with(getContext())
                    .load(imageResources.get(i))
                    .fitCenter()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imageView);
        }

        setAdapter(pagerViews);
    }

    private void setAdapter(final ArrayList<ImageView> pagerViews) {

        BannerPagerAdapter bannerPagerAdapter =
                new BannerPagerAdapter(pagerViews);

        autoScrollViewPager.setAdapter(bannerPagerAdapter);
//        indicator.setViewPager(autoScrollViewPager);

        autoScrollViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                pointGroup.getChildAt(position).setEnabled(true);
                pointGroup.getChildAt(lastPosition).setEnabled(false);
                lastPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        startAutoScroll();
    }

    public void startAutoScroll() {
        autoScrollViewPager.startAutoScroll();
    }

    public void stopAutoScroll() {
        autoScrollViewPager.stopAutoScroll();
    }

    public class BannerPagerAdapter extends PagerAdapter {

        protected List<ImageView> Images;

        public BannerPagerAdapter(List<ImageView> Images) {
            this.Images = Images;
        }

        @Override
        public int getCount() {
            return Images.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(Images.get(position));
            return Images.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            container.removeView(Images.get(position));
        }
    }

}
